<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>天天生鲜-商品列表</title>
    <link rel="shortcut icon" href="images/logo.png">
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/goods.css">
</head>

<body>
<div id="yc-goods">
    <!-- 头部  -->
    <div class="header_con">
        <div class="header">
            <div class="welcome fl">欢迎来到天天生鲜</div>
            <div class="fr">
                <div class="login_info fl" v-if="onlogin">
                    欢迎：<em>{{loginName}}</em>
                </div>
                <div class="login_btn fl" v-else>
                    <a href="login.html">登录</a>
                    <span> | </span>
                    <a href="register.html">注册</a>
                </div>
                <div class="user_link fl" v-if="onlogin">
                    <span> | </span>
                    <a href="user_center_info.html">用户中心</a>
                    <span> | </span>
                    <a href="cart.html">我的购物车</a>
                    <span> | </span>
                    <a href="user_center_order.html">我的订单</a>
                    <span>|</span>
                    <a href="" @click.prevent="logout()">退出登录</a>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜素框 -->
    <div class="search_bar clearfix">
        <a href="index.html" class="logo fl"><img src="images/logo.png"></a>
        <div class="search_con fl">
            <input type="text" placeholder="搜素商品" name="" class="input_text fl">
            <input type="button" value="搜索" class="input_btn fr">
        </div>
        <div class="guest_cart fr">
            <a href="cart.html" class="cart_name fl">我的购物车</a>
            <div class="goods_count fl" id="show_count">{{goodsCount}}</div>
        </div>
    </div>

    <!-- 全部商品分类 -->
    <div class="navbar_con">
        <div class="navbar clearfix">
            <!-- 动态下拉框 -->
            <div class="subnav_con fl">
                <h1 class="fl">全商品分类</h1>
                <span></span>
                <ul class="subnav">
                    <li><a href="#1&新鲜水果" class="fruit" @click="FindGoods('1&新鲜水果')">新鲜水果</a></li>
                    <li><a href="#2&海鲜水产" class="seafood" @click="FindGoods('2&海鲜水产')">海鲜水产</a></li>
                    <li><a href="#3&猪牛羊肉" class="meet" @click="FindGoods('3&猪牛羊肉')">猪牛羊肉</a></li>
                    <li><a href="#4&禽类蛋品" class="egg" @click="FindGoods('4&禽类蛋品')">禽类蛋品</a></li>
                    <li><a href="#5&新鲜蔬菜" class="vegetables" @click="FindGoods('5&新鲜蔬菜')">新鲜蔬菜</a></li>
                    <li><a href="#6&速冻食品" class="ice" @click="FindGoods('6&速冻食品')">速冻食品</a></li>
                </ul>
            </div>
            <ul class="navlist fl">
                <li><a href="index.html">首页</a></li>
                <li class="interval">|</li>
                <li><a href="">手机生鲜</a></li>
                <li class="interval">|</li>
                <li><a href="">抽奖</a></li>
            </ul>
        </div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb" id="breadcrumb">
        <a href="javascript:void(0)">全部分类</a>
        <span>&gt;</span>
        <a href="javascript:void(0)" id="text"></a>
    </div>

    <!-- 商品展示区域-->
    <div class="main_wrap clearfix">
        <!-- 新品推荐 -->
        <div class="l_wrap fl clearfix">
            <div class="new_goods">
                <h3>新品推荐</h3>
                <ul>
                    <li>
                        <a href="#"><img src="images/goods/goods003.jpg"></a>
                        <h4><a href="#">牛奶草莓</a></h4>
                        <div class="prize">￥16.80</div>
                    </li>
                    <li>
                        <a href="#"><img src="images/goods/goods009.jpg"></a>
                        <h4><a href="#">海南帝王蕉</a></h4>
                        <div class="prize">￥99.00</div>
                    </li>
                </ul>
            </div>
        </div>
        <!-- 热门类型查询 -->
        <div class="r_wrap fr clearfix">
            <div class="sort_bar">
                <a href="javascript:void(0);" id="normal" class="type active">默认</a>
                <a href="javascript:void(0);" id="price" class="type ">价格</a>
                <a href="javascript:void(0);" id="manUse" class="type ">人气</a>
            </div>
            <ul class="goods_type_list clearfix show1">
                <li v-for="good in goods">
                    <a :href="'details.html#'+good.gno"><img :src="'./'+good.pics"></a>
                    <h4><a :href="'details.html#'+good.gno">{{good.gname}}</a></h4>
                    <div class="operate">
                        <span class="prize">￥{{good.price}}</span>
                        <span class="unit">{{good.price}}/{{good.weight}}</span>
                        <a href="javascript:void(0);" @click="addCart(good.gno)" class="add_goods" title="加入购物车"></a>
                    </div>
                </li>
            </ul>
            <!-- 分页栏-->
            <div class="pagenation">
                <ul>
                    <li><a href="#">上一页</a></li>
                    <li v-for="i in totalPage">
                        <a href="javascript:void(0);" @click="findPage(i)" v-if="i==pageNo" class="active">{{i}}</a>
                        <a href="javascript:void(0);" @click="findPage(i)" v-else>{{i}}</a>
                    </li>
                    <li><a href="#">下一页</a></li>
                </ul>
            </div>
        </div>

    </div>
    <!-- 版权所有 -->
    <div class="footer">
        <div class="foot_link">
            <a href="#">关于我们</a> <span> | </span>
            <a href="#">联系我们</a> <span> | </span>
            <a href="#">招聘广告</a> <span> | </span>
            <a href="#">友情链接</a>
        </div>
        <p>CopyRight &copy; 2019 衡阳市源辰信息科技有限公司 All Rights Reserverd</p>
        <p>电话：0734-8355998 湘ICP备16015987号</p>
    </div>

</div>

<!--  注意引入顺序 -->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/slide.js"></script>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script src="js/qs.js"></script>
<script>
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    let begin ="http://localhost:20001/";
    let security = "freshgood-security/";
    let goods = "freshgood-goods/";
    let cart = "freshgood-cart/";

    Vue.prototype.axios = axios;
    axios.interceptors.request.use(config => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            } else {
                config.headers.Authorization = '';
            }
            console.log(token);
            console.log(config);
            return config;
        }, error => {
            return Promise.reject(error);
        }
    );
    function selectName() {
        const Url = window.location.href;
        const decodedUrl = decodeURI(Url);
        const goodType = decodedUrl.split("#")[1].split("&")[1];
        $("#text").html(goodType);
        // console.log(goodType); // 输出当前网页的完整URL
    }

    let tno;
    let page = 1;
    let rows = 5;

    let app = new Vue({

        el: "#yc-goods",
        data: {
            onlogin: false,
            outlogin: true,
            loginName: '匿名',
            mno: 0,
            goods: {},
            carts: {},
            goodsCount: 0,
            total: 0,
            totalPage: 0,
            pageNo: 1,
        },
        mounted: function () {
            // 记载页面时，发送请求检查用户是否登录请求   分类查看前四条商品
            axios.all([checkLogin(), findGoods(), selectName()])
                .then(axios.spread((rs1, rs2)=>{
                    if(rs1.data.code === 0){
                        //说明未登录
                        this.onlogin = false;
                        this.outlogin = true;
                    }else{
                        this.loginName = rs1.data.user.nickName;
                        this.carts = rs1.data.cartList;
                        this.mno=rs1.data.user.mno;
                        this.onlogin = true;
                        this.outlogin = false;
                        // this.goodsCount = rs1.data.goodsCount;
                        if(this.carts != null){
                            for (let i = 0; i < this.carts.length; i++) {
                                this.goodsCount += this.carts[i].num;
                            }
                        }
                    }
                    this.goods = rs2.data.goods;
                    this.total = rs2.data.total;
                    if(this.total % rows ===0){
                        this.totalPage = this.total/rows;
                    }else{
                        this.totalPage = parseInt(1+ (this.total/rows));
                    }
                }));
        },
        methods: {
            logout: function () {
                axios(loginOut()).then(
                    this.onlogin = false,
                    this.outlogin = true,
                )
                location.href = "login.html";
            },
            addCart: function (gno) {
                if (this.onlogin == false) {
                    //暂未登录
                    alert("暂未登录，请先登录后在添加购物车！");
                    location.href = "login.html";
                    return;
                }
                let flag = 0;
                //判断商品在购物车中是否已存在
                // if (this.carts.length > 0) {
                //
                // }
                if (this.carts != null) {
                    for (let i = 0; i < this.carts.length; i++) {
                        if (this.carts[i].gno == gno) {
                            flag = 1;
                            //有修改
                            axios.post(begin+cart+"cart/addCart", qs.stringify({
                                 gno: gno, cno: this.carts[i].cno, num: 1
                            })).then(rs => {
                                if (rs.data > 0) {
                                    //添加成功
                                    this.carts[i].num = this.carts[i].num + 1;
                                    this.goodsCount++;
                                } else {
                                    alert("添加失败！");
                                }
                            });
                        }
                    }
                }
                if (flag == 0) {
                    //购物车没有
                    axios({
                            url:begin+cart+"cart/addCart",
                            params:{
                                num: 1,
                                gno: gno},
                            method:"get"
                    }).then(rs => {
                        let cno = rs.data;
                        if ("0" == cno) {
                            alert("添加失败");
                        } else {
                            //更新数组
                            this.carts.push({gno: gno, cno: cno, num: 1, mno: this.mno});
                            this.goodsCount++;
                        }
                    })
                }
            },

            findPage: function (pnum) {
                this.pageNo = pnum;
                axios({
                    url: "http://localhost:20001/freshgood-goods/goods/findByPage",
                    method: "get",
                    params: {tno: tno, page: this.pageNo, pageSize: rows}
                }).then(rs => {
                    this.goods = rs.data.goods;
                })

            },
            FindGoods: function (s) {
                var hash = s; //#1&新鲜水果
                console.log(hash)
                hash = hash.replace("#", "").split("&");
                tno = hash[0];
                $("text").html(hash[1]);
                axios({
                    url: "http://localhost:20001/freshgood-goods/goods/findByPage",
                    method: "get",
                    params: {tno: tno, page: page, pageSize: rows}
                }).then(rs => {
                    this.goods = rs.data.goods;
                    this.total = rs.data.total;
                    if (this.total % rows === 0) {
                        this.totalPage = this.total / rows;
                    } else {
                        this.totalPage = parseInt(1 + (this.total / rows));
                    }
                    selectName()
                })
            },
        },
    });

    function loginOut() {
        return axios.get(begin+security+"security/freshgood/loginOut");

    }

    //检查用户是否登录
    function checkLogin() {
        return axios.get(begin+security+"security/freshgood/loginCheck");

    }

    //分类查询前四条商品
    function findGoods() {
        var hash = decodeURI(location.hash); //#1&新鲜水果
        if (hash == '' || hash.indexOf("&") <= 0) {
            location.href = "index.html";
            return;
        }
        hash = hash.replace("#", "").split("&");
        tno = hash[0];
        $("text").html(hash[1]);
        return axios({
            url: "http://localhost:20001/freshgood-goods/goods/findByPage",
            method: "get",
            params: {tno: tno, page: page, pageSize: rows}
        });
    }

    // //获取url地址栏
    // function getQueryString(name) {
    //     //正则表达式
    //     var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    //     ///获取url中从问号（"?"符）开始的字符串
    //     var url = decodeURI(window.location.search);
    //     //截取？后面的字符串
    //     var r = url.substr(1).match(reg);
    //     if (r != null) {
    //         //decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
    //         return decodeURI(r[2]);
    //     }
    //     return null;
    //

    // //热门查询动态样式
    // //给我们热门类型查询做点击事件
    // $(".type").on("click",function(){
    // 	//默认查询方式
    // 	var type = "id";
    // 	//移除原来的active的样式
    // 	$(".type").removeClass("active");
    // 	//获取此时点击的对象的文本是什么
    // 	var check = $(this).html();
    // 	//判断
    // 	if(check == "默认"){
    // 		$("#normal").addClass("active");
    // 	}
    // 	if(check == "价格"){
    // 		$("#price").addClass("active");
    // 		type = "gprice"
    // 	}
    // 	if(check == "人气"){
    // 		$("#manUse").addClass("active");
    // 		type = "gsales"
    // 	}
    // 	//与后台交互 暂不处理
    // 	/*
    // 	$.post("url",{type:type},function(data){
    //
    // 	});
    // 	*/
    // 	//模拟动态页面
    // 	var str = '';
    // 	var data = Math.round(Math.random()*22+1);
    // 	console.log(data);
    // 	for(var i= 1;i <data;i++){
    // 		if(i<10){
    // 			str += ' <li> <a href="#"><img src="images/goods/goods00'+i+'.jpg"></a>';
    // 		}else{
    // 			str += ' <li> <a href="#"><img src="images/goods/goods0'+i+'.jpg"></a>';
    // 		}
    //          str +=  '<h4><a href="#">牛奶草莓</a></h4>'+
    // 				'<div class="operate">'+
    // 				'<span class="prize">￥16.80</span>'+
    // 			   '<span class="unit">16.80/500g</span>'+
    // 				'<a href="cart.html" class="add_goods" title="加入购物车"></a>'+
    // 				'</div></li>';
    // 	}
    // 	//写入网页指定的标签中
    // 	$(".show1").html(str);
    //
    // })
    //
    //
</script>
</body>
</html>
